/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    CCell,InputLine, LineColumn, SuffixInput, Table, TableBody, TableHead, TableRow, Text,
} from "customize-easy-ui-component";
import {
    InspectRecordLayout, InternalItemProps, RepLink, SelectInput, useItemInputControl,
} from "../../common/base";
import {useMeasureInpFilter} from "../../common/hooks";
import {floatInterception, objNestSet} from "../../../common/tool";
import {useOmnipotentPrefMove, useOmnipotentPrefTitle} from "../../hook/useOmnipotentPref";
import {JumpPref} from "../../common/general";
import {检查结论选} from "../../tools";

/*借用的常见模型[name, prefixCols[{t:'title1',s: 3,cs:-1}, {},], item, unit,[defaultColValue1, 2]]
 最后的默认值配置数组，这里借用当成固定配置“允差”栏目的内容。 语义处理思路比较接近的。
 增加 itemAssist 配置，当作本配置的扩展=联动性。
 * */
export const items性能复测 = [
    ['复起升速', [], '满载最大起升速度变化值 (mm/s)', 'mm/s', ['±30',] ],
    ['复运行速', [], '满载最大运行速度变化值 （km/h）', 'km/h', ['±2',] ],
    ['复下滑量', [], '货叉自然下滑量变化值 （mm）', 'mm', ['≤15',] ],
    ['复倾角变', [], '门架（或货叉）自倾角变化值 （°）', '°', ['≤1',] ],
] as any;
//【耦合@联动性@】和上面主配置items性能复测一一对应的； 辅助的， 更多关联配置： [试验前测量值存储字段名， 跳转tag，参看表叙述, 四舍五入位数, 试验结果精度]；
const itemAssist =[
    ['满载升v', 'MaxLiftSpeed', <div>附表3 最大起升速度、下降速度测量记录表（C3.1.1和 C3.1.2）/测定结果（满载）</div>, undefined,0],
    ['满载行v', 'MaxSpeed', <div>附表6 最大行驶速度试验记录表（C3.3）/满载/试验结果</div>, undefined,1],
    //关联存储还会有两个来源字段的情况。 自动精度规整  c:'四', d:0
    [['小下滑o','大下滑o'], 'Measure', <div>附表1 测量结果记录/C3.1.3/额定起重量≤10000kg 或 额定起重量＞10000kg</div>, 0,0],
    //自动精度规整 c:'四',d:2,
    ['倾角变o', 'Measure', <div>附表1 测量结果记录/C3.1.3/门架或者货叉倾角的自然变化量</div>, 2,2]
] as any;
export const prepareRtValc=(inp:any)=>itemAssist.map(([names, tag, desc, odg, rsdg]: any, i: number) => {
    let oldv=Array.isArray(names)?  (inp?.[names[0]] ?? inp?.[names[1]] ??'') : (inp?.[names] ??'');
    if(undefined!==odg)  oldv=floatInterception(oldv,odg,);
    const nname=items性能复测[i]?.[0];
    let diff=Number(inp?.[nname]?.v) - Number(oldv);        //=试验结果
    diff=Number(floatInterception(diff,rsdg,));
    return {oldv, diff};
});
/**存储检查 ['小下滑o','大下滑o'] 不需要了，实际来自其他的编辑器。
 * */
export const itemA性能复测: string[] = ['性能复测r'];
items性能复测.forEach(([name, title, initIsp]:any, i: number) => {
    itemA性能复测.push(name as string);
});
//不能直接用 const itemAm=itemA性能复测;         JS 不可变性？
const itemAm=[ ...itemA性能复测 ];
itemAssist.forEach(([names, ]:any, i: number) => {
    if(Array.isArray(names))    itemAm.push(...names);
    else itemAm.push(names);
});
export const PerforRetest =
    React.forwardRef((
        {children, show, alone = true, refWidth, label, rep}: InternalItemProps, ref
) => {
    const {inp, setInp} = useItemInputControl({ref});
    const [getInpFilter] = useMeasureInpFilter(null, itemAm,);
    const titNode=useOmnipotentPrefTitle({config: items性能复测, });
                //if (Array.isArray(itemAssist[0]) && typeof itemAssist[0][0] === 'string') { ；
    const assist = React.useMemo(() =>prepareRtValc(inp), [inp]);
    return (
        <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                             alone={alone} label={label!}>
            <Text variant="h5">{label}：</Text>
            {items性能复测.map(([name, titlps, item, unit,dfvs]: any, i: number) => {
                return (<React.Fragment key={i}>
                    <div css={{display: 'flex', flexWrap: 'wrap', alignItems: 'center'}}>
                        {titNode[i]}&nbsp;
                        &nbsp;试验前测量值={assist[i]?.oldv} {unit}
                        &nbsp;来自<JumpPref rep={rep} tag={itemAssist[i][1]}>{itemAssist[i][2]}</JumpPref>
                        <InputLine label='试验后复测值'>
                            <SuffixInput value={inp?.[name]?.v || ''}
                                          onChange={e=>objNestSet(name, 'v', e.currentTarget.value, inp, setInp)}>{unit}</SuffixInput>
                        </InputLine>
                    </div>
                </React.Fragment>);
            })}
            <hr/>试验结果:
            {items性能复测.map(([name, titlps, item, unit,dfvs]: any, i: number) => {
                return (<React.Fragment key={i}>
                    <div css={{display: 'flex', flexWrap: 'wrap', alignItems: 'center'}}>
                       项目{i+1}&nbsp;=
                        <Text css={{fontSize: '1.1rem'}}>&nbsp; {assist[i]?.diff ||''} </Text>
                        <Text>&nbsp;&nbsp; 允差：{dfvs?.[0]} ;</Text>
                    </div>
                </React.Fragment>);
            })}
            结果判定:
            <LineColumn>
                <InputLine label='附表12-4 强化试验后性能复测-结果判定'>
                    <SelectInput value={inp?.性能复测r || ''} list={检查结论选}
                                 onChange={e => setInp({...inp, 性能复测r: e.currentTarget.value || undefined})}/>
                </InputLine>
            </LineColumn>
            { children }
        </InspectRecordLayout>
    );
});

const guidancer = (assist:any[], op?: boolean) => {
    return (orc: any, name: string, i: number, item: any, xmcspan: number, unit: any, config: any[][]) => <>
        <CCell colSpan={xmcspan}>{item}</CCell>
        <CCell>{orc?.[name]?.r ?? config[i]?.[4][0]}</CCell>
        <CCell>{assist[i]?.oldv ||''}</CCell>
        <CCell>{orc?.[name]?.v ?? '／'}</CCell>
        <CCell>{assist[i]?.diff ||''}</CCell>
        {0===i && <CCell rowSpan={4}>{orc?.性能复测r ?? '／'}</CCell>}
    </>;
};
/*试验结果=自动计算值； 4项的试验前测量值都是其它表格已经录入的！！
* */
export const PerforRetestVw = ({orc, rep, label, children}: { orc: any, rep: any, label: string, children?: any}
) => {
    const tag = 'PerforRetest';
    const assist = React.useMemo(() =>prepareRtValc(orc), [orc]);
    const [renderSpeedTest] = useOmnipotentPrefMove({orc,
                config: items性能复测, tag:'PrototypeInsp',itemRender:guidancer(assist,true), pcols: 0, noNo: false, unitCel: false});
    return <>
        <Text variant="h4" css={{
            marginTop: '1rem', "@media print": {paddingBottom: '4rem', pageBreakInside: 'avoid'}
        }}>{label}</Text>
        <Table id={tag} fixed={ ["4.6%","%","18.1%","12.1%","12.1%","10%","8.4%"] } tight miniw={800}
                css={{borderCollapse: 'collapse', "@media print": {marginTop: '-4rem'}}}>
            <TableHead>
                <TableRow>
                    <CCell>序号</CCell><CCell>性能指标名称</CCell><CCell>试验后复测值的允差</CCell>
                    <CCell>试验前测量值</CCell><CCell>试验后复测值</CCell><CCell>试验结果</CCell><CCell>结果判定</CCell>
                </TableRow>
            </TableHead>
            <TableBody>
            <RepLink ori rep={rep} tag={'PerforRetest'}>
                {renderSpeedTest}
            </RepLink>
            </TableBody>
        </Table>
        { children }
    </>;
};
